#include "vnode_map.h"

// ---- class VNodeReal ----
VNodeReal::VNodeReal(const char *path, bool dir)
{
	m_path = path;
	m_type = dir ? Type::dir : Type::file;
}

const char *VNodeReal::get_real_path() const
{
	return m_path.c_str();
}

bool VNodeReal::is_real() const
{
	return true;
}


// ---- class VNodeDirMap ----
VNodeDirMap::VNodeDirMap()
{
	m_dir = 0;
}

VNodeDirMap::~VNodeDirMap()
{
	if(m_dir) {
		closedir(m_dir);
	}

	for(auto n : m_real_nodes) {
		delete n;
	}
}

bool VNodeDirMap::open(const char *path)
{
	close();

	if(!(m_dir = opendir(path))) {
		return false;
	}
	m_targ_path = path;
	return true;
}

void VNodeDirMap::close()
{
	if(m_dir) {
		closedir(m_dir);
		m_dir = 0;
		m_targ_path = "";
	}
}

bool VNodeDirMap::is_open() const
{
	return m_dir != nullptr;
}

VNode *VNodeDirMap::lookup(char *path)
{
	// try to open this as a directory
	DIR *dir = opendir(path);
	if(dir) {
		closedir(dir);
		VNodeReal *vrdir = new VNodeReal(path, true);
		m_real_nodes.push_back(vrdir);
		return vrdir;
	}

	// might be a file...
	FILE *fp = fopen(path, "r");
	if(fp) {
		fclose(fp);
		VNodeReal *vrfile = new VNodeReal(path);
		m_real_nodes.push_back(vrfile);
		return vrfile;
	}

	return nullptr;
}
